using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Web;
using Microsoft.SharePoint;
using PS.WebParts.Rollup.Core;
using PS.WebParts.Rollup.Query;

namespace PS.WebParts.Rollup
{
    class SqlRollupStrategy : IRollupStrategy
    {
        private ARollupDataSourceView view;
        string contentType;


        public SqlRollupStrategy(ARollupDataSourceView view, string contentType)
        {
            if (view == null)
                throw new ArgumentNullException("view");
            this.view = view;
            this.contentType = contentType;
        }

        public DataTable GetData(SPWeb web)
        { 
            try
            {
                string[] lists = view.Lists;
                List<DataTable> dtList = new List<DataTable>(lists.Length);

                string query = view.Query;
                foreach (string list in lists)
                {
                    PSSiteDataQuery siteDataQuery;

                    siteDataQuery = GetQuery(query, web, list);
                  
                    RollUpQueryWebScope scope = view.Scope;

                    DataTable dtResults;
                    if (scope == RollUpQueryWebScope.SiteCollection)
                        dtResults = siteDataQuery.GetRollupData(web.Site);
                    else
                        dtResults = siteDataQuery.GetRollupData(web, scope == RollUpQueryWebScope.Recursive);

                    view.Stats.SetPostProcessingBegin();

                    dtList.Add(dtResults);
                  //  siteDataQuery.Dispose();
                }

                if (dtList.Count == 1)
                    return dtList[0];
                else
                {
                    return JoinProcessor.Union(dtList);
                }
                
            }
            catch (UnauthorizedAccessException)
            {
                view.LogError("User has no access to web: " + web.Title);
                return new DataTable();
            }
            catch (Exception e)
            {
                view.LogError("Error while rolling up data at the following web: " + web.Title, e);
                return new DataTable();
            }
        }

        private PSSiteDataQuery GetQuery(string str, SPWeb web, string list)
        {
            HttpContext ctx = HttpContext.Current;

            ICacheProvider cacheProvider = ctx != null ? new AspNetDataSchemaCache(ctx) : (ICacheProvider)new PSSiteDataSchemaCache();

            PSSiteDataQuery siteDataQuery = new PSSiteDataQuery(cacheProvider);

            if (string.IsNullOrEmpty(str) && !string.IsNullOrEmpty(contentType))
            {
                str = string.Format("<Where><Eq><FieldRef Name='ContentType' /><Value Type='Text'>{0}</Value></Eq></Where>", contentType);
            }
            else
            {
                if (str.Contains("&lt;") && str.Contains("&gt;"))
                {
                    str = HttpUtility.HtmlDecode(str);
                }

                str = str.TrimStart('\r', '\n', '\t');
                str = str.TrimEnd('\r', '\n', '\t');

                if (!str.Contains("<Where>") 
                    && !str.StartsWith("<OrderBy>", true, CultureInfo.InvariantCulture))
                {
                    str = "<Where>" + str + "</Where>";
                }

                str = ARollupDataSourceView.ReplaceQueryLiveFields(str, web, null, null, view.Parameters);
            }

            siteDataQuery.Query = str;

            uint? limit = view.QueryRowLimit;
            if (limit != null)
            {
                siteDataQuery.RowLimit = (uint)limit;
            }

            siteDataQuery.Lists.Hidden = true;
            if (list != "*")
            {
                int val;
                if (int.TryParse(list, out val))
                {
                    if (val > 99)
                        siteDataQuery.Lists.ServerTemplate = val;
                    else if (val >= 0)
                        throw new ArgumentOutOfRangeException("List", val,
                                                              "BaseType values are no longer supported in SQL mode");
                } else
                {
                    siteDataQuery.Lists.ListTitle = list;
                }
            }
            else
                siteDataQuery.Lists.ServerTemplate = 100;

            foreach (FieldInfo field in view.Fields)
            {
                siteDataQuery.Fields.Add(field.GetSchemaName());
                if(!string.IsNullOrEmpty(field.Match))
                {
                    siteDataQuery.FieldMatches.Add(field.GetSchemaName(), field.Match);
                }
            }

            if (!(view is SqlRollupDataView))
            {
                siteDataQuery.Options.IncludeListData = IncludeMetaDataOptions.IDs;
                if (this.view.IncludeListData)
                    siteDataQuery.Options.IncludeListData |= IncludeMetaDataOptions.Item | IncludeMetaDataOptions.List |
                                                             IncludeMetaDataOptions.Web;
            } else
            {
                siteDataQuery.Options.IncludeListData = ((SqlRollupDataView)view).IncludeMetadata;

            }
            return siteDataQuery;
        }
    }
}
